<template>
  <com-card>
    <!-- <div slot="com_header">角色列表</div> -->
    <div slot="com_content">
      <el-table :data="dataObj" border type="expand">
        <el-table-column type="expand">
          <template #default="{ row }">
            <!-- 一级 -->
            <el-row v-for="item in row.children" :key="item.id">
              <hr />
              <el-col :span="4">
                <!-- 判断他是否还有下一级，如果有就不显示X如果没有就显示X -->
                <el-tag v-if="item.children && item.children.length != 0"
                  >{{ item.authName }}<i class="el-icon-caret-right"></i
                ></el-tag>
                <el-tag v-else closable @close="handleClose(row, item.id)">{{
                  item.authName
                }}</el-tag>
              </el-col>

              <!-- 二级 -->
              <el-col :span="20">
                <el-row v-for="tow in item.children" :key="tow.id">
                  <el-col :span="4">
                    <el-tag
                      v-if="tow.children && tow.children.length != 0"
                      type="success"
                      >{{ tow.authName }}<i class="el-icon-caret-right"></i
                    ></el-tag>
                    <el-tag
                      v-else
                      closable
                      @close="handleClose(row, tow.id)"
                      type="success"
                      >{{ tow.authName }}</el-tag
                    >
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span="20" class="item_col">
                    <el-row v-for="woow in tow.children" :key="woow.id">
                      <!-- 这里的woow.id表示最后一级的id -->
                      <el-tag
                        type="danger"
                        @close="handleClose(row, woow.id)"
                        closable
                        >{{ woow.authName }}
                      </el-tag>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="角色名称" prop="roleName">
          <template #default="{ row }">
            <div v-if="row.flag">
              <input type="text" v-model="row.roleName" />
            </div>
            <div v-else>
              {{ row.roleName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
          <template #default="{ row }">
            <div v-if="row.flag">
              <input type="text" v-model="row.roleDesc" />
            </div>
            <span v-else>{{ row.roleDesc }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot="header">
            <el-button type="success" size="small" @click="tianjia"
              >添加角色</el-button
            >
          </template>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button
                icon="el-icon-edit"
                size="small"
                :type="row.flag ? 'success' : 'primary'"
                @click="xiugai(row)"
                >{{ row.flag ? "完成" : "修改" }}</el-button
              >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                @click="del(row.id)"
                >删除</el-button
              >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="small"
                @click="power(row)"
                >分配权限</el-button
              >
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
      <!-- 添加角色的弹窗 -->
      <el-dialog
        title="添加角色"
        :visible.sync="dialogVisible"
        width="30%"
        :close-on-click-modal="false"
      >
        <el-form size="small" label-width="80px" :model="formObj">
          <el-form-item label="角色名称">
            <el-input v-model="formObj.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述 ">
            <el-input v-model="formObj.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色的弹窗、 -->
      <el-dialog
        title="分配角色"
        :visible.sync="treeVisible"
        width="50%"
        :close-on-click-modal="false"
      >
        <!-- node-key;指定复选框绑定的属性 -->
        <el-tree
          :data="treeData"
          show-checkbox
          default-expand-all
          node-key="id"
          ref="tree"
          highlight-current
          :props="defaultProps"
        >
        </el-tree>

        <span slot="footer" class="dialog-footer">
          <el-button type="info" @click="treeVisible = false">取 消</el-button>
          <el-button type="warning" @click="resetChecked">清空</el-button>
          <el-button type="success" @click="setall">全选</el-button>
          <el-button type="primary" @click="treeup">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </com-card>
</template>

<script>
import { api_fenpei } from "../../api/user.js";
import {
  api_del,
  api_delete,
  api_add,
  api_right,
  api_setright,
  api_update,
} from "../../api/roles.js";
import ComCard from "../../components/comCard/index.vue";
export default {
  components: {
    ComCard,
  },
  data() {
    return {
      dialogVisible: false, // 添加角色弹窗默认关闭
      treeVisible: false, //分配权限弹窗默认关闭
      dataObj: [], // 渲染表格数据的
      formObj: {}, //添加角色
      treeData: [], //分配权限
      defaultProps: {
        //指定树形控件中显示标题的属性和子菜单的属性
        children: "children",
        label: "authName",
      },
      // 定义获取所有最后一级权限的id数组
      rightid: [],
      // 定义当前分配角色的id
      roleId: 0,
      allid: [], //记录全选的数组
      flag: false,
      // bianji:{},
    };
  },
  mounted() {
    this.query();
  },
  methods: {
    // 点击修改按钮时触发的函数

    async xiugai(row) {
      if (row.flag) {
        let rst = await api_update({
          id: row.id,
          roleName: row.roleName,
          roleDesc: row.roleDesc,
        });
        let { msg, status } = rst.meta;
        if (status == 200) {
            this.$message({
            type: "success",
            message: "修改成功!",
          });
        }
       
      }
       row.flag = !row.flag;
    },

    // 点击分配权限时触发的函数
    async power(row) {
      this.rightid = []; //清空树形组件中的复选框
      this.treeVisible = true;

      // 为当前jueseid赋值
      this.roleId = row.id;
      // 获取所有的tree的数据
      let rst = await api_right({ url: "tree" });
      this.treeData = rst.data;
      console.log(rst.data);
      this.setrightid(row, this.rightid);
      // 获取所有的三级权限的id数组
      const treeallobj = {
        children: [],
      };
      treeallobj.children = rst.data;
      this.setrightid(treeallobj, this.allid);
      console.log(this.allid);
      //处理数据回填，在回填之前要获取到当前角色所有的权限且是最后一句的权限id值
      this.$refs.tree.setCheckedKeys(this.rightid);
    },
    // 定义递归函数在函数中调用自己本身，用于将所有的最后一级的权限id添加到数组中
    setrightid(obj, arr) {
      if (!obj.children) {
        arr.push(obj.id);
        return;
      }
      obj.children.forEach((item) => {
        this.setrightid(item, arr);
      });
    },
    // 点击分配权限中确认按钮是触发的函数
    async treeup() {
      // 获取到roleId和rids（所有选中的树形组件的id拼接为一个数组然后转为string字符串以逗号将所有的id分隔）
      let halfkeys = this.$refs.tree.getHalfCheckedKeys();
      let currkety = this.$refs.tree.getCheckedKeys();
      let rids = [...halfkeys, ...currkety].join(",");
      let rst = await api_setright({ roleId: this.roleId, rids });
      // let {status}=rst.meta;
      if (rst.meta.status == 200) {
        this.treeVisible = false;
        this.query();
      }
      console.log(rst);
    },
    // 全选
    setall() {
      this.$refs.tree.setCheckedKeys(this.allid);
    },
    // 树形组件清空
    resetChecked() {
      this.$refs.tree.setCheckedKeys([]);
    },

    // 点击添加时触发的函数
    tianjia() {
      let { roleName, roleDesc } = this.formObj;
      this.formObj = { roleName, roleDesc };
      this.dialogVisible = true;
    },
    //点击确认框的时候触发的函数
    async save() {
      let rst = await api_add(this.formObj);
      let { status } = rst.meta;

      if (status == 201) {
        this.query();
        this.formObj.roleName = "";
        this.formObj.roleDesc = "";
        this.$message({ type: "success", message: "添加角色成功" });
        this.dialogVisible = false;
      }
    },
    // 点击展开行的删除
    async handleClose(row, rightId) {
      // 和pai接口中的值对应
      let rst = await api_delete({ roleId: row.id, rightId });
      let { msg, status } = rst.meta;
      this.status = status;
      if (rst.meta.status == 200) {
        row.children = rst.data;
      }
    },

    // 获取表单信息
    async query() {
      let rst = await api_fenpei();
      let { data } = rst; //单独结构data
      data.map((item) => {
        item.flag = false;
      });
      this.dataObj = data; //把data的数据赋值给dataObj
      // console.log(rst);
    },
    // 点击删除时触发的函数
    del(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let rst = await api_del({ id });
          // let {data}=rst;
          // this.dataObj = data;
          this.query();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style lang="less" scoped>
.item_col {
  display: flex;
  // align-items: center;
  height: 40px;
}
</style>